#include "bsp_pwm.h"

/**
 * @brief PWM2的初始化
 *
 */
void PWM_Init() {
  PWM_GPIO1_IO09_Init();
  PWM_Disabled(PWM2);
  PWM_Software_Reset(PWM2);
  PWM2->PWMCR = 0;

  /* PWM2时钟选择和分频*/
  PWM2->PWMCR |= (0x1 << 16);
  PWM2->PWMCR |= (65 << 4);

  /* PWM2输出配置*/
  PWM2->PWMCR |= (0x1 << 18);

  PWM_Period(PWM2, 1000);

  PWM_Sample(PWM2, 0);
}

/**
 * @brief       设置PWM采样寄存器
 *
 * @param PWM    PWM_Type
 * @param value  0x0001---0xFFFE
 */
void PWM_Sample(PWM_Type *PWM, unsigned int value) {
  PWM->PWMSAR = (value & 0xffff);
}

/**
 * @brief       设置PWM周期寄存器
 *
 * @param PWM    PWM_Type
 * @param value  0x0001---0xFFFE
 */
void PWM_Period(PWM_Type *PWM, unsigned int value) {
  PWM->PWMPR = ((value - 2) & 0xffff);
}

/**
 * @brief   PWM的软件复位
 *
 * @param PWM PWM_Type
 */
void PWM_Software_Reset(PWM_Type *PWM) {
  PWM->PWMCR |= (0x1 << 3);
  while ((PWM->PWMCR >> 3) & 0x1) {
  }
}
/**
 * @brief     PWM的使能
 *
 * @param PWM PWM_Type
 */
void PWM_Enabled(PWM_Type *PWM) { PWM->PWMCR |= (0x1); }
/**
 * @brief    PWM的关闭
 *
 * @param PWM PWM_Type
 */
void PWM_Disabled(PWM_Type *PWM) { PWM->PWMCR &= ~(0x1); }

/**
 * @brief GPIO1_IO09的PWM模式初始化
 *
 */
void PWM_GPIO1_IO09_Init() {
  IOMUXC_SetPinMux(IOMUXC_GPIO1_IO09_PWM2_OUT, 0);
  IOMUXC_SetPinConfig(IOMUXC_GPIO1_IO09_PWM2_OUT, 0X10B0);

  gpio_pin_config_t config;
  config.direction = kGPIO_DigitalOutput;
  config.outputLogic = 1;
  config.interruptMode = kGPIO_NoIntmode;

  gpio_init(GPIO1, 9, &config);
}